package cn.xshi.job.publisher;

import cn.xshi.common.util.JsonUtil;
import cn.xshi.job.service.JobLogService;
import cn.xshi.job.model.JobLog;
import cn.xshi.job.vo.ChannelEntity;
import cn.xshi.job.vo.RequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
/**
 * Netty 工具类
 */
@Slf4j
@Component
public class NettyUtil {

    @Resource
    JobLogService jobLogService;

    /**
     * 发送消息
     * @param channelEntity
     */
    public boolean sendMessage(ChannelEntity channelEntity){
        boolean result = true;
        try {
            if(null == channelEntity.getChannel()){
                log.info("未能获取到通道号");
                result = false;
            }else{
                RequestInfo requestInfo = channelEntity.getRequestInfo();
                channelEntity.getChannel().writeAndFlush(JsonUtil.toJson(requestInfo));
            }
            new Thread(new JobLogWorker(channelEntity,"Success")).start();
        }catch (Exception e){
            log.error("发送消息异常：",e);
            result =  false;
            new Thread(new JobLogWorker(channelEntity,"Fail")).start();
        }
        return result;
    }

    /**
     *
     */
    class JobLogWorker implements Runnable{

        private String flag;

        ChannelEntity channelEntity;

        public JobLogWorker(){

        }

        /**
         *
         * @param channelEntity
         * @param flag
         */
        public JobLogWorker(ChannelEntity channelEntity,String flag){
            this.channelEntity = channelEntity;
            this.flag = flag;
        }

        public void run() {
            try {
                JobLog jobLog = new JobLog();
                Date date = new Date();
                jobLog.setCreateTime(date);
                jobLog.setUpdateTime(date);
                jobLog.setName(channelEntity.getRequestInfo().getJobHandlerEntity().getJobName());
                jobLog.setJobKey(channelEntity.getRequestInfo().getJobHandlerEntity().getJobName());
                jobLog.setContent(""+channelEntity.getRequestInfo().getObj());
                jobLog.setFlag(flag);
                jobLogService.addJobLog(jobLog);
            } catch (Exception e) {
                log.info("调度任务记录日志异常:{}",e);
            }
        }
    }
}
